<?php

namespace app\admin\model;

use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use think\Db;
use think\Log;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text'
    ];

    public function getOriginData()
    {
        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            if (isset($changedata['money'])) {
                $origin = $row->getOriginData();
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score'])) {
                $origin = $row->getOriginData();
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }

    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['prevtime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['logintime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['jointime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function findInfoByCondition($condition = [], $isLock = 0)
    {
        if ($isLock == 1) {
            $user = self::where($condition)->lock(true)->find();
        } else {
            $user = self::where($condition)->find();
        }

        if ($user) {
            unset($user['password']);
        }
        return $user;
    }

    public static function assignUsers($params = [], $sort, $order, $offset, $limit)
    {
        $where = [];
        $whereOr = [];
        if (isset($params['id'])) {
            $where['u.id'] = $params['id'];
        }
        if (isset($params['nickname'])) {
            $where['u.nickname'] = ['like', $params['nickname'].'%'];
        }
        if (isset($params['category_id']) && $params['category_id']) {
            $where['uc.category_id'] = $params['category_id'];
        }
        if (isset($params['work_status'])) {
            if ($params['work_status'] == 1) {  // 空闲中
                $where['pa.uid'] = null;
            } elseif ($params['work_status'] == 2) {    // 工作中
                $where['pa.work_status'] = ['in', [0,1]];
            } elseif ($params['work_status'] == 3) {    // 已结束
                $where['pa.work_status'] = 2;
            } elseif ($params['work_status'] == 4) {    // 已退出
                $where['pa.work_status'] = 3;
            }
        }
        $list = db('user')->alias('u')->join('user_category uc', 'uc.uid = u.id', 'left')->join('project_assign pa', 'pa.uid = u.id and pa.category_id = uc.category_id', 'left')->field('u.*,uc.category_id, pa.work_status, pa.uid as assign_uid')->where($where)->group('u.id')->order($sort, $order)->limit($offset, $limit)->select();
        return $list;
    }

    public static function assignUsersCount($params = [])
    {
        $where = [];
        if (isset($params['id'])) {
            $where['u.id'] = $params['id'];
        }
        if (isset($params['nickname'])) {
            $where['u.nickname'] = ['like', $params['nickname'].'%'];
        }
        if (isset($params['category_id']) && $params['category_id']) {
            $where['uc.category_id'] = $params['category_id'];
        }
        if (isset($params['work_status'])) {
            if ($params['work_status'] == 1) {  // 空闲中
                $where['pa.uid'] = null;
            } elseif ($params['work_status'] == 2) {    // 工作中
                $where['pa.work_status'] = ['in', [0,1]];
            } elseif ($params['work_status'] == 3) {    // 已结束
                $where['pa.work_status'] = 2;
            } elseif ($params['work_status'] == 4) {    // 已退出
                $where['pa.work_status'] = 3;
            }
        }
        $count = db('user')->alias('u')->join('user_category uc', 'uc.uid = u.id', 'left')->join('project_assign pa', 'pa.uid = u.id', 'left')->where($where)->count('distinct u.id');
        return $count;
    }

    public static function getWorkStausName($status)
    {
        $name = '空闲中';
        if ($status == 1) {
            $name = '工作中';
        }
        return $name;
    }

    public static function saveData($condition = [], $data = [])
    {
        if ($condition && $data) {
            return self::where($condition)->update($data);
        }
    }

}
